package com.network.retrofit_rx.download;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;

/**
 * Created by QiQi on 2017/8/23.
 */

public class DownLoadService extends Service {

    private final static String TAG = DownLoadService.class.getSimpleName();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private final String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "DownLoad";

    private String destFileName = "app.apk";

    private Context mContext;
    private int preProgress = 0;
    private Retrofit.Builder retrofit;
    private DownLoadUtil downLoadUtil = DownLoadUtil.getInstance();
    private String ip;

    public static void startService(Context context, String downLoadUrl, String ip) {
        Intent intent = new Intent(context, DownLoadService.class);
        intent.putExtra("loadUrl", downLoadUrl);
        intent.putExtra("ip", ip);
        context.startService(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext = this;
        ip = intent.getStringExtra("ip");
        String downLoadUrl = intent.getStringExtra("loadUrl");
        loadFile(downLoadUrl);
        return super.onStartCommand(intent, flags, startId);
    }

    private void loadFile(String downLoadUrl) {
        if (TextUtils.isEmpty(downLoadUrl)) {
            return;
        }

        if (retrofit == null) {
            retrofit = new Retrofit.Builder();
        }

        retrofit.client(initOkHttpClient())
                .baseUrl(ip)
                .build()
                .create(IFileLoad.class)
                .loadFile(downLoadUrl)
                .enqueue(new FileCallback(destFileDir, destFileName) {
                    @Override
                    public void onSuccess(File file) {
                        Log.i(TAG, "下载成功");
                        installApk(file);
                        downLoadUtil.onSuccess(file);
                        stopSelf();
                    }

                    @Override
                    public void onProgress(long progress, long total) {
                        updateProgress(progress, total);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        downLoadUtil.onFailure(t);
                        stopSelf();
                    }
                });

    }


    /**
     * 安装软件
     *
     * @param file
     */
    private void installApk(File file) {
        Uri uri = Uri.fromFile(file);
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        // 执行意图进行安装
        mContext.startActivity(install);
    }

    /**
     * 初始化OkHttpClient
     *
     * @return
     */
    private OkHttpClient initOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(100000, TimeUnit.SECONDS);
        builder.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse
                        .newBuilder()
                        .body(new FileResponseBody(originalResponse.body()))//将自定义的ResposeBody设置给它
                        .build();
            }
        });
        return builder.build();
    }

    private void updateProgress(long progress, long total) {
        int currentProgress = (int) progress;
        if (preProgress < currentProgress) {
            downLoadUtil.onProgress(progress, total);
        }
        preProgress = (int) progress;
    }

}
